const express = require('express')
const app = express()
const port = 3000
const bodyParser = require('body-parser')
const mysqldb = require('./model/db')
const dayjs = require('dayjs')
/* const dayjs = require('dayjs') */
const params = []
/**
 * 全系统允许跨域处理 这段配置要再new出express实例的时候就要设置了，放在所有的api前面，不然没有效果
*/
app.all("*", function (req, res, next) {
    //设置允许跨域的域名，*代表允许任意域名跨域
    res.header("Access-Control-Allow-Origin", "*");
    //允许的header类型
    res.header("Access-Control-Allow-Headers", "*");
    //跨域允许的请求方式
    res.header("Access-Control-Allow-Methods", "*");
    if (req.method.toLowerCase() == 'options')
        res.send(200);  //让options尝试请求快速结束
    else
        next();
});

//使用bodyoarser中间件获取数据
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())

//获取打卡列表数据
app.get('/current', (req, res) => {
    let sql = `SELECT *FROM current;`
    mysqldb(sql, params, (result) => {
        res.json(result)
    })
})
app.get('/hesuan', (req, res) => {
    let sql = `SELECT *FROM hesuan;`
    mysqldb(sql, params, (result) => {
        res.json(result)
    })
})
app.get('/jiankangma', (req, res) => {
    let sql = `SELECT *FROM jiankangma;`
    mysqldb(sql, params, (result) => {
        res.json(result)
    })
})


/* 
    获取用户信息
    getUser
*/
app.get('/getuser/:id/:type', (req, res) => {

    console.log(req.params);
    let params = [req.params.id]
    let sql = req.params.type == 2 ? `SELECT *FROM student where stu_id=?;` : `SELECT *FROM teacher where teacher_id=?;`
    console.log(sql);
    mysqldb(sql, params, (result) => {
        if (!result.length) {
            res.json({
                code: 404,
                msg: '用户不存在'
            })
            return
        }
        console.log(result);
        res.json(result)
    })
})
/* 
    查看今天有没有打卡
*/
app.post('/istrue', (req, res) => {
    let params = [req.body.stu_id]
    let sql = `SELECT *FROM student where stu_id=?;`
    mysqldb(sql, params, (result) => {
        if (!result.length) {
            res.json('用户不存在').status(404)
            return
        }
        let sql = `SELECT *FROM health where u_id=?;`
        mysqldb(sql, params, (result) => {
            const today = dayjs(Date.now()).format('YYYY-MM-DD')
            for (let i = 0; i < result.length; i++) {
                let sqlDay = dayjs(result[i].time).format('YYYY-MM-DD')
                if (today == sqlDay) {
                    result[i].current = `[${result[i].current}]`
                    result[i].current = JSON.parse(result[i].current)
                    result[i].hesuan = Number(result[i].hesuan)
                    result[i].jiankangma = Number(result[i].jiankangma)
                    res.json({
                        msg: '今天以打卡',
                        code: 'yes',
                        result: result[i]
                    })
                    return
                }
            }
            res.json({
                msg: '今天未打卡',
                code: ''
            })

        })

    })
})

/* 
    test
*/
app.post('/daka', (req, res) => {
    console.log(req.body);
    let params = [req.body.sno]
    let sql = `SELECT *FROM student where stu_id=?;`
    mysqldb(sql, params, (result) => {
        if (!result.length) {
            res.json('用户不存在').status(404)
            return
        }
        req.body.current = req.body.current.toString()
        console.log(req.body);
        let params = [req.body.current, req.body.hesuan, req.body.jiankangma, req.body.place, req.body.sno]
        let sql = `INSERT INTO health (current,hesuan,jiankangma,place,time,u_id) VALUES(?,?,?,?,NOW(),?);`
        mysqldb(sql, params, (result) => {
            res.json(result)
        })
    })
})


/* 
    打卡记录
    get 
*/
app.get('/record/:sno', (req, res) => {
    let params = [req.params.sno]
    let sql = `select *from student where stu_id=?`
    mysqldb(sql, params, (result) => {
        if (!result.length) {
            res.json('用户不存在')
            return
        }
        let sql = `select *from health where u_id=? order by time desc`
        mysqldb(sql, params, (result) => {
            for (let i = 0; i < result.length; i++) {
                result[i].time = dayjs(result[i].time).format('YYYY-MM-DD')
            }

            for (let i = 0; i < result.length; i++) {
                result[i].current = `[${result[i].current}]`
                result[i].current = JSON.parse(result[i].current)
                result[i].hesuan = Number(result[i].hesuan)
                result[i].jiankangma = Number(result[i].jiankangma)
            }
            res.json({
                msg: '查询成功',
                code: 200,
                result,
            })
        })
    })
})


app.post('/leave', (req, res) => {
    req.body.starttime = dayjs(req.body.starttime).format('YYYY-MM-DD HH:mm:ss')
    req.body.endtime = dayjs(req.body.endtime).format('YYYY-MM-DD HH:mm:ss')
    let sql = "INSERT INTO `leave`(u_id,leavetype,reason,starttime,endtime,state,createtime) VALUES(?,?,?,?,?,0,NOW())"
    let params = [req.body.u_id, req.body.leaveType, req.body.reason, req.body.starttime, req.body.endtime]
    mysqldb(sql, params, (result) => {
        if (result.affectedRows > 0) {
            res.json({
                msg: '提交成功',
                code: 200
            })
        } else {
            res.status(404).json('提交失败')
        }
    })
})

//获取请假条
app.get('/getleave', (req, res) => {
    let sql = "SELECT *FROM `leave` WHERE u_id=?"
    let params = [req.query.u_id]
    mysqldb(sql, params, (result) => {

        res.json(result)
    })
})
//获取xx老师管理的请假条
app.get('/getStuleave', (req, res) => {
    let sql = `SELECT s.stu_id,s.username,leavetype,reason,starttime,endtime,state,l.createtime,l.leave_id,c.classes FROM student as s
    INNER JOIN class as c
    ON s.class_id=c.class_id
    INNER JOIN teacherforclass as tc
    ON tc.class_id=c.class_id
    INNER JOIN teacher as t
    ON tc.teacher_id=t.teacher_id
    INNER JOIN`+ "`leave`" + ` as l
    ON l.u_id=s.stu_id
    WHERE t.teacher_id=?; `
    let params = [req.query.u_id]
    mysqldb(sql, params, (result) => {

        res.json(result)
    })
})

/* 请假条通过 */
app.get('/setleavepass', (req, res) => {
    console.log(req.query.leave_id);
    let sql = "UPDATE `leave` SET state=2 WHERE leave_id=?; "
    let params = [req.query.leave_id]
    mysqldb(sql, params, (result) => {
        console.log(result);
        res.json(result)
    })
})
/* 请假条不通过 */
app.get('/setleavenopass', (req, res) => {
    let sql = "UPDATE `leave` SET state=1 WHERE leave_id=?; "
    let params = [req.query.leave_id]
    mysqldb(sql, params, (result) => {
        console.log(result);
        res.json(result)
    })
})
/* 获取某老师班今日打卡的信息 */
app.get('/getdakastu', (req, res) => {
    let sql = `SELECT *FROM 
    teacher AS t
    INNER JOIN teacherforclass as tc
    ON t.teacher_id=tc.teacher_id
    INNER JOIN student as s
    ON s.class_id=tc.class_id
    INNER JOIN health as h
    ON h.u_id=s.stu_id
    where t.teacher_id=?
    ;`
    let params = [req.query.u_id]
    mysqldb(sql, params, (result) => {
        const today = dayjs(Date.now()).format('YYYY-MM-DD')
        let daka = result.filter((item) => {
            return dayjs(item.time).format('YYYY-MM-DD') == today
        })
        for (let i = 0; i < daka.length; i++) {
            daka[i].current = `[${daka[i].current}]`
            daka[i].current = JSON.parse(daka[i].current)
        }
        res.json({
            code: 200,
            msg: '获取成功',
            daka,
        })
    })
})

/* 查看某班还未打卡的学生 */
app.get('/getnodakastu', (req, res) => {
    let sql = `SELECT s.stu_id,s.username,c.classes FROM student as s 
    INNER JOIN class AS c
    ON  s.class_id=c.class_id
    INNER JOIN teacherforclass as tc
    ON tc.class_id=c.class_id
    INNER JOIN teacher as t
    ON t.teacher_id=tc.teacher_id
    WHERE NOT EXISTS(
    SELECT u_id FROM health as h
    WHERE s.stu_id=h.u_id
    AND date_format(now(),'%Y-%m-%d')=date_format(time,'%Y-%m-%d') 
    ) 
    AND t.teacher_id=?;`
    let params = [req.query.u_id]
    mysqldb(sql, params, (result) => {

        res.json({
            code: 200,
            msg: '获取成功',
            result
        })
    })
})
app.listen(port, () => console.log(`http://127.0.0.1:${port}`))